const todoUtils = window.markAnything.utils;

// 添加待办事项
const addTodo = async (content) => {
  try {
    await todoUtils.checkStorageAvailable();
    const result = await chrome.storage.local.get(['todos']);
    const todos = result.todos || [];
    
    const todo = {
      id: Date.now(),
      content,
      url: window.location.href,
      pageTitle: document.title,
      createdAt: new Date().toISOString(),
      completed: false
    };
    
    todos.push(todo);
    await chrome.storage.local.set({ todos });
    return todo.id;
  } catch (error) {
    console.error('保存待办事项失败:', error);
    throw error;
  }
};

// 获取所有待办事项
const getAllTodos = async () => {
    try {
      await utils.checkStorageAvailable();
      const result = await chrome.storage.local.get(['todos']);
      const todos = result.todos || [];
      
      // 按完成状态和时间排序
      return todos.sort((a, b) => {
        // 未完成的排在前面
        if (a.completed !== b.completed) {
          return a.completed ? 1 : -1;
        }
        // 同样状态的按时间倒序
        return new Date(b.createdAt) - new Date(a.createdAt);
      });
    } catch (error) {
      console.error('获取待办事项失败:', error);
      throw error;
    }
  };

// 切换待办事项状态
const toggleTodoStatus = async (id) => {
    try {
      await utils.checkStorageAvailable();
      const result = await chrome.storage.local.get(['todos']);
      let todos = result.todos || [];
      
      // 找到并更新待办状态
      todos = todos.map(todo => {
        if (todo.id === id) {
          return {
            ...todo,
            completed: !todo.completed,
            completedAt: !todo.completed ? new Date().toISOString() : null
          };
        }
        return todo;
      });
      
      // 保存更新后的待办列表
      await chrome.storage.local.set({ todos });
    } catch (error) {
      console.error('更新待办状态失败:', error);
      throw error;
    }
  };

// 删除待办事项
const deleteTodo = async (id) => {
  try {
    await todoUtils.checkStorageAvailable();
    const result = await chrome.storage.local.get(['todos']);
    const todos = result.todos || [];
    const newTodos = todos.filter(todo => todo.id !== id);
    
    if (newTodos.length === todos.length) {
      throw new Error('待办事项不存在');
    }
    
    await chrome.storage.local.set({ todos: newTodos });
  } catch (error) {
    console.error('删除待办事项失败:', error);
    throw error;
  }
};

// 更新待办事项
const updateTodo = async (id, updates) => {
  try {
    await todoUtils.checkStorageAvailable();
    const result = await chrome.storage.local.get(['todos']);
    const todos = result.todos || [];
    const todoIndex = todos.findIndex(todo => todo.id === id);
    
    if (todoIndex !== -1) {
      todos[todoIndex] = { ...todos[todoIndex], ...updates };
      await chrome.storage.local.set({ todos });
      return todos[todoIndex];
    }
    throw new Error('待办事项不存在');
  } catch (error) {
    console.error('更新待办事项失败:', error);
    throw error;
  }
};

// 显示待办编辑器
const showTodoEditor = async () => {
    // 检查是否已存在编辑器
    const existingEditor = document.querySelector('.todo-input-container');
    if (existingEditor) {
      const isTodoEditor = existingEditor.querySelector('h2').textContent === '待办事项';
      existingEditor.remove();
      if (isTodoEditor) {
        return;
      }
    }
  
    utils.closeAllPopups();
  
    const container = document.createElement('div');
    container.className = 'todo-input-container todo-cards-container';
  
    const header = document.createElement('div');
    header.className = 'todo-header';
    header.innerHTML = `
      <div class="todo-header-left">
        <h2>待办事项</h2>
        <button class="toggle-completed-button">显示已完成</button>
      </div>
      <button class="todo-close-button">×</button>
    `;
  
    const contentWrapper = document.createElement('div');
    contentWrapper.className = 'todo-cards-wrapper';
  
    // 创建新增待办按钮
    const addTodoButton = document.createElement('button');
    addTodoButton.className = 'add-todo-button';
    addTodoButton.innerHTML = '+ 新建待办';
    
    // 待办列表容器
    const todoList = document.createElement('div');
    todoList.className = 'todo-cards-list';
  
    // 已完成列表容器（默认隐藏）
    const completedList = document.createElement('div');
    completedList.className = 'todo-cards-list completed-list hidden';
    completedList.innerHTML = '<h3 class="completed-list-title">已完成事项</h3>';
  
    contentWrapper.appendChild(addTodoButton);
    contentWrapper.appendChild(todoList);
    contentWrapper.appendChild(completedList);
    container.appendChild(header);
    container.appendChild(contentWrapper);
    document.body.appendChild(container);
  
    const closeButton = header.querySelector('.todo-close-button');
    const toggleCompletedButton = header.querySelector('.toggle-completed-button');
    
    closeButton.addEventListener('click', () => container.remove());
    toggleCompletedButton.addEventListener('click', () => {
      completedList.classList.toggle('hidden');
      toggleCompletedButton.classList.toggle('active');
      toggleCompletedButton.textContent = completedList.classList.contains('hidden') ? '显示已完成' : '隐藏已完成';
    });
  
    // 创建新待办卡片的函数
    const createNewTodoCard = (isNew = false) => {
      const todoCard = document.createElement('div');
      todoCard.className = 'todo-card' + (isNew ? ' new' : '');
      
      const input = document.createElement('textarea');
      input.className = 'todo-card-input';
      input.placeholder = '输入待办事项...';
      
      const actions = document.createElement('div');
      actions.className = 'todo-card-actions';
      
      const saveButton = document.createElement('button');
      saveButton.className = 'todo-card-save';
      saveButton.textContent = '保存';
      
      const cancelButton = document.createElement('button');
      cancelButton.className = 'todo-card-cancel';
      cancelButton.textContent = '取消';
      
      actions.appendChild(saveButton);
      actions.appendChild(cancelButton);
      
      todoCard.appendChild(input);
      todoCard.appendChild(actions);
      
      // 添加到列表最前面
      todoList.insertBefore(todoCard, todoList.firstChild);
      input.focus();
  
      // 保存按钮事件
      saveButton.addEventListener('click', async () => {
        const content = input.value.trim();
        if (!content) {
          utils.showNotification('待办内容不能为空', true);
          return;
        }
  
        try {
          const id = await todoRepository.addTodo(content);
          utils.showNotification('待办事项已添加');
          // 将编辑卡片转换为普通待办卡片
          createTodoItemCard({ id, content, completed: false, createdAt: new Date().toISOString() }, todoCard);
          // 更新顶部滚动条
          updateTodoScrollbar();
        } catch (error) {
          utils.showNotification('添加失败', true);
        }
      });
  
      // 取消按钮事件
      cancelButton.addEventListener('click', () => {
        todoCard.remove();
      });
  
      // 快捷键支持
      input.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.shiftKey)) {
          e.preventDefault();
          saveButton.click();
        } else if (e.key === 'Escape') {
          cancelButton.click();
        }
      });
  
      return todoCard;
    };
  
    // 创建待办事项卡片的函数
    const createTodoItemCard = (todo, existingCard = null) => {
      const todoCard = existingCard || document.createElement('div');
      todoCard.className = 'todo-card' + (todo.completed ? ' completed' : '');
      todoCard.dataset.id = todo.id;
      
      // Add checkbox for completed todos
      if (todo.completed) {
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'todo-selection-checkbox';
        checkbox.checked = window.selectedCompletedTodos?.some(t => t.id === todo.id) || false;
        checkbox.addEventListener('change', (e) => {
          if (e.target.checked) {
            window.selectedCompletedTodos = window.selectedCompletedTodos || [];
            window.selectedCompletedTodos.push(todo);
          } else {
            window.selectedCompletedTodos = window.selectedCompletedTodos || [];
            window.selectedCompletedTodos = window.selectedCompletedTodos.filter(t => t.id !== todo.id);
          }
          window.updateSummaryButton?.();
        });
        todoCard.appendChild(checkbox);
      }
      
      const content = document.createElement('div');
      content.className = 'todo-card-content';
      content.textContent = todo.content;
      
      const meta = document.createElement('div');
      meta.className = 'todo-card-meta';
      meta.textContent = new Date(todo.createdAt).toLocaleString();
      
      const actions = document.createElement('div');
      actions.className = 'todo-card-actions';
      
      const completeButton = document.createElement('button');
      completeButton.className = 'todo-card-complete';
      completeButton.innerHTML = todo.completed ? '↺' : '✓';
      completeButton.title = todo.completed ? '撤回' : '完成';
      
      const editButton = document.createElement('button');
      editButton.className = 'todo-card-edit';
      editButton.innerHTML = '✎';
      editButton.title = '编辑';
      
      const copyButton = document.createElement('button');
      copyButton.className = 'todo-card-copy';
      copyButton.innerHTML = '⎘';
      copyButton.title = '复制';
      
      const deleteButton = document.createElement('button');
      deleteButton.className = 'todo-card-delete';
      deleteButton.innerHTML = '×';
      deleteButton.title = '删除';
      
      actions.appendChild(completeButton);
      actions.appendChild(editButton);
      actions.appendChild(copyButton);
      actions.appendChild(deleteButton);
  
      // 如果是转换已有卡片，先清空内容
      if (existingCard) {
        todoCard.innerHTML = '';
      }
      
      todoCard.appendChild(content);
      todoCard.appendChild(meta);
      todoCard.appendChild(actions);
  
      if (!existingCard) {
        if (todo.completed) {
          // Remove empty message if it exists
          const emptyMessage = completedList.querySelector('.todo-cards-empty');
          if (emptyMessage) {
            emptyMessage.remove();
          }
          completedList.appendChild(todoCard);
        } else {
          // Remove empty message if it exists
          const emptyMessage = todoList.querySelector('.todo-cards-empty');
          if (emptyMessage) {
            emptyMessage.remove();
          }
          todoList.appendChild(todoCard);
        }
      }
  
      // 编辑按钮事件
      editButton.addEventListener('click', () => {
        todoCard.classList.add('editing');
        const input = document.createElement('textarea');
        input.className = 'todo-edit-input';
        input.value = todo.content;
        
        const editActions = document.createElement('div');
        editActions.className = 'todo-edit-actions';
        
        const saveButton = document.createElement('button');
        saveButton.className = 'todo-edit-save';
        saveButton.textContent = '保存';
        
        const cancelButton = document.createElement('button');
        cancelButton.className = 'todo-edit-cancel';
        cancelButton.textContent = '取消';
        
        editActions.appendChild(saveButton);
        editActions.appendChild(cancelButton);
        
        content.style.display = 'none';
        todoCard.insertBefore(input, meta);
        actions.style.display = 'none';
        todoCard.appendChild(editActions);
        
        input.focus();
        
        const handleSave = async () => {
          const newContent = input.value.trim();
          if (newContent && newContent !== todo.content) {
            todo.content = newContent;
            content.textContent = newContent;
            try {
              await todoRepository.updateTodo(todo.id, { content: newContent });
              utils.showNotification('更新成功');
              // 更新顶部滚动区域
              updateTodoScrollbar();
            } catch (error) {
              utils.showNotification('更新失败', true);
            }
          }
          exitEditMode();
        };
        
        const exitEditMode = () => {
          todoCard.classList.remove('editing');
          content.style.display = '';
          input.remove();
          actions.style.display = '';
          editActions.remove();
        };
        
        saveButton.addEventListener('click', handleSave);
        cancelButton.addEventListener('click', exitEditMode);
        
        input.addEventListener('keydown', (e) => {
          if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.shiftKey)) {
            e.preventDefault();
            handleSave();
          } else if (e.key === 'Escape') {
            exitEditMode();
          }
        });
      });
  
      // 其他按钮事件保持不变
      completeButton.addEventListener('click', async () => {
        try {
          await todoRepository.toggleTodoStatus(todo.id);
          todoCard.classList.add('moving');
          setTimeout(() => {
            todoCard.remove();
            // Check if the list is empty immediately after removing the card
            const list = todo.completed ? completedList : todoList;
            const remainingTodos = list.querySelectorAll('.todo-card:not(.moving)').length;
            if (remainingTodos === 0) {
              list.innerHTML = todo.completed ? 
                '<h3 class="completed-list-title">已完成事项</h3><div class="todo-cards-empty">暂无已完成事项</div>' : 
                '<div class="todo-cards-empty">暂无待办事项</div>';
            }
            // Create the new card in the other list
            todo.completed = !todo.completed;
            createTodoItemCard(todo);
            updateTodoScrollbar();
          }, 300);
          utils.showNotification(todo.completed ? '已撤回待办' : '已标记为完成');
        } catch (error) {
          utils.showNotification('操作失败', true);
        }
      });
  
      copyButton.addEventListener('click', () => {
        navigator.clipboard.writeText(todo.content)
          .then(() => utils.showNotification('已复制到剪贴板'))
          .catch(() => utils.showNotification('复制失败', true));
      });
  
      deleteButton.addEventListener('click', async () => {
        try {
          await todoRepository.deleteTodo(todo.id);
          todoCard.classList.add('deleting');
          setTimeout(() => {
            todoCard.remove();
            const list = todo.completed ? completedList : todoList;
            const remainingTodos = list.querySelectorAll('.todo-card:not(.deleting)').length;
            if (remainingTodos === 0) {
              list.innerHTML = todo.completed ? 
                '<h3 class="completed-list-title">已完成事项</h3><div class="todo-cards-empty">暂无已完成事项</div>' : 
                '<div class="todo-cards-empty">暂无待办事项</div>';
            }
            updateTodoScrollbar();
          }, 300);
          utils.showNotification('待办事项已删除');
        } catch (error) {
          utils.showNotification('删除失败', true);
        }
      });
  
      return todoCard;
    };
  
    // 新增待办按钮点击事件
    addTodoButton.addEventListener('click', () => {
      const emptyTodo = todoList.querySelector('.todo-cards-empty');
      if (emptyTodo) {
        emptyTodo.remove();
      }
      createNewTodoCard(true);
    });
  
    // 加载已有待办事项
    try {
      const todos = await todoRepository.getAllTodos();
      const activeTodos = todos.filter(todo => !todo.completed);
      const completedTodos = todos.filter(todo => todo.completed);
  
      if (activeTodos.length === 0) {
        todoList.innerHTML = '<div class="todo-cards-empty">暂无待办事项</div>';
      } else {
        activeTodos.forEach(todo => createTodoItemCard(todo));
      }
  
      if (completedTodos.length === 0) {
        completedList.innerHTML = '<h3 class="completed-list-title">已完成事项</h3><div class="todo-cards-empty">暂无已完成事项</div>';
      } else {
        completedTodos.forEach(todo => createTodoItemCard(todo));
      }
    } catch (error) {
      console.error('加载待办失败:', error);
      todoList.innerHTML = '<div class="todo-cards-error">加载失败</div>';
    }
  };

  // 创建顶部待办滚动展示
function createTodoScrollbar() {
  // Create container if it doesn't exist
  let container = document.querySelector('.todo-scrollbar-container');
  if (!container) {
    container = document.createElement('div');
    container.className = 'todo-scrollbar-container';
    document.body.appendChild(container);
    
    // Add close button
    const closeButton = document.createElement('button');
    closeButton.className = 'todo-scrollbar-close';
    closeButton.innerHTML = '×';
    closeButton.title = '关闭待办滚动区域';
    closeButton.onclick = () => {
      container.style.display = 'none';
      document.body.style.marginTop = '0';
      const floatingButtons = document.querySelector('.floating-buttons-container');
      if (floatingButtons) floatingButtons.style.marginTop = '0';
      const leftNote = document.querySelector('.left-note-container');
      if (leftNote) leftNote.style.marginTop = '0';
    };
    container.appendChild(closeButton);

    // Create content container
    const content = document.createElement('div');
    content.className = 'todo-scrollbar-content';
    container.appendChild(content);
  }

  // Update content
  updateTodoScrollbar();
}
  
  // 更新顶部待办滚动内容
  async function updateTodoScrollbar() {
    const container = document.querySelector('.todo-scrollbar-container');
    const content = container?.querySelector('.todo-scrollbar-content');
    if (!container || !content) return;
  
    // 如果设置为不显示，直接返回
    if (!currentSettings.showTodoScroll) {
      container.style.display = 'none';
      return;
    }
  
    try {
      const todos = await todoRepository.getAllTodos();
      const activeTodos = todos.filter(todo => !todo.completed);
  
      if (activeTodos.length === 0) {
        container.style.display = 'none';
        // 移除所有相关元素的顶部边距
        document.body.style.marginTop = '0';
        const floatingButtons = document.querySelector('.floating-buttons-container');
        if (floatingButtons) floatingButtons.style.marginTop = '0';
        const leftNote = document.querySelector('.left-note-container');
        if (leftNote) leftNote.style.marginTop = '0';
        return;
      }
  
      // 显示容器并恢复所有相关元素的顶部边距
      container.style.display = 'block';
      document.body.style.marginTop = '36px';
      const floatingButtons = document.querySelector('.floating-buttons-container');
      if (floatingButtons) floatingButtons.style.marginTop = '36px';
      const leftNote = document.querySelector('.left-note-container');
      if (leftNote) leftNote.style.marginTop = '36px';
  
      // 更新内容
      content.innerHTML = '';
      const todoText = activeTodos.map(todo => `
        <span class="todo-scrollbar-item">
          <span class="todo-scrollbar-actions">
            <button class="todo-scrollbar-btn copy" title="复制">⎘</button>
            <button class="todo-scrollbar-btn complete" title="标记为已完成">✓</button>
          </span>
          ${todo.content}
        </span>
      `).join('');
      
      // 重置所有样式和类
      content.className = 'todo-scrollbar-content';
      content.style.transform = 'none';
      content.innerHTML = todoText;
      
      // 添加按钮事件监听
      content.querySelectorAll('.todo-scrollbar-item').forEach((item, index) => {
        const todo = activeTodos[index];
        const copyBtn = item.querySelector('.todo-scrollbar-btn.copy');
        const completeBtn = item.querySelector('.todo-scrollbar-btn.complete');
        
        copyBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          navigator.clipboard.writeText(todo.content)
            .then(() => utils.showNotification('已复制到剪贴板'))
            .catch(() => utils.showNotification('复制失败', true));
        });
        
        completeBtn.addEventListener('click', async (e) => {
          e.stopPropagation();
          try {
            const todoItem = item;
            todoItem.style.animation = 'fadeOut 0.3s ease-out forwards';
            await todoRepository.toggleTodoStatus(todo.id);
            setTimeout(() => {
              todoItem.remove();
              updateTodoScrollbar();
            }, 300);
            utils.showNotification('已标记为完成');
          } catch (error) {
            utils.showNotification('操作失败', true);
          }
        });
      });
      
      // 获取实际内容宽度（考虑padding）
      const contentWidth = Array.from(content.children)
        .reduce((total, item) => total + item.offsetWidth + 40, 0) - 40; // 40px是item的margin-right
      const containerWidth = container.clientWidth - 40; // 40px是container的padding
      
      if (contentWidth > containerWidth) {
        // 内容超出容器宽度，需要滚动
        const duplicatedContent = content.innerHTML;
        content.innerHTML = duplicatedContent + duplicatedContent; // 添加第二份内容用于无缝滚动
        content.classList.add('scrolling');
        
        // 为复制的内容也添加事件监听
        content.querySelectorAll('.todo-scrollbar-item').forEach((item, index) => {
          const todo = activeTodos[index % activeTodos.length];
          const copyBtn = item.querySelector('.todo-scrollbar-btn.copy');
          const completeBtn = item.querySelector('.todo-scrollbar-btn.complete');
          
          copyBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            navigator.clipboard.writeText(todo.content)
              .then(() => utils.showNotification('已复制到剪贴板'))
              .catch(() => utils.showNotification('复制失败', true));
          });
          
          completeBtn.addEventListener('click', async (e) => {
            e.stopPropagation();
            try {
              const todoItem = item;
              todoItem.style.animation = 'fadeOut 0.3s ease-out forwards';
              await todoRepository.toggleTodoStatus(todo.id);
              setTimeout(() => {
                todoItem.remove();
                updateTodoScrollbar();
              }, 300);
              utils.showNotification('已标记为完成');
            } catch (error) {
              utils.showNotification('操作失败', true);
            }
          });
        });
      } else {
        // 内容未超出容器宽度，靠左显示
        content.classList.add('static');
      }
    } catch (error) {
      console.error('更新顶部待办滚动条失败:', error);
      container.style.display = 'none';
    }
  }

// // 导出到全局对象
window.markAnything.todoRepository = {
  getAllTodos,
  addTodo,
  updateTodo,
  deleteTodo,
  toggleTodoStatus,
  showTodoEditor,
  updateTodoScrollbar,
  createTodoScrollbar
};
